package com.mcptt.http.operator.sys;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.cloudptt.api.product.log.Log;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mcptt.comm.CommonFunc;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.model.McpttLoginInfo;
import com.mcptt.http.operator.IHttpOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SysHttpAuthLoader implements Callback{
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url_Auth = ":10010/ias/ue-uas-auth";;
	private static final int ConnectionTimeout = 30 * 1000;
	private static final int SoTimeout = 30 * 1000;
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private SysConfig config = null;

	protected IHttpOpCb callback = null;

	public SysHttpAuthLoader(SysConfig config,IHttpOpCb callback)
	{
		this.config = config;
		this.callback = callback;
	}

	public void doHttpAuth() {
		new Thread(new Runnable(){
			@Override
			public void run()
			{
				try {
					doHttpAuthThread();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doHttpAuthThread() throws Exception
	{
		if(config != null)
		{
			String svrIp = config.getHttpServerInfo().getIp();
			String url = HTTP_KEY + svrIp + Sub_Url_Auth;

			McpttLoginInfo mcpttLoginInfo = config.getMcpttLoginInfo();

			McIdInfo userInfo = mcpttLoginInfo.getMcIdInfo();
			int type = userInfo.getType();
			String num = userInfo.getMcId();
			String pwd = userInfo.getPwd();

			Log.debug(getClass(), "doHttpAuthThread url = " + url + " userInfo = " + userInfo);
			Map<String, String> params = new HashMap<String, String>();
//			if(type == McIdInfo.TYPE_FUNC)
//			{
//				params.put("Type", "" + type);
//				params.put("DeviceID", num);
//			}
//			else {
			params.put("Type", "" + type);
			params.put("ID", num);
			params.put("Password", pwd);
//			}

			OkHttpUtils.getInstance().doPutJson(url, params, this);
		}

//		Log.debug(getClass(), "doHttpGet url = " + url);
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("AccntID", num);
//		params.put("Password", pwd);
//		OkHttpUtils.getInstance().doPutJson(url, params, this);
	}

	private void sendOpResultMsg(boolean isSuc,int cause)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.arg1 = cause;
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.arg1 = cause;
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
				case OP_SUC:
					if(callback != null)
					{
						int cause = msg.arg1;
						callback.onOpResult(IHttpOpCb.Id_Auth,true,cause,"");
					}
					break;
				case OP_FAILED:
					if(callback != null)
					{
						int cause = msg.arg1;
						callback.onOpResult(IHttpOpCb.Id_Auth,false,cause,"");
					}
					break;
			}
		}
	};

	@Override
	public void onFailure(Call arg0, IOException e) {
		// TODO Auto-generated method stub
		if(e != null)
		{
			e.printStackTrace();
		}
		Log.debug(getClass(), "onFailure e = " + e);
		sendOpResultMsg(false,70090);
	}

	@Override
	public void onResponse(Call arg0, Response response) throws IOException {
		// TODO Auto-generated method stub
		if(response == null)
		{
			sendOpResultMsg(false,70091);
			return;
		}

		Log.debug(getClass(), "onResponse isSuccessful = " + response.isSuccessful());
		if(response.isSuccessful())
		{

			try
			{
				InputStream  instreams = response.body().byteStream();
				String content = CommonFunc.convertStreamToString(instreams);//.convertStreamToString(instreams,"user_not_registered");
				Log.debug(getClass(), "onResponse Content = " + content);

				JsonParser jsonParser = new JsonParser();
				JsonObject obj = jsonParser.parse(content).getAsJsonObject();
				Log.debug(getClass(), "onResponse obj = " + obj);

				int cause = obj.get("Cause").getAsInt();

				Log.debug(getClass(), "onResponse cause = " + cause);

				if(config != null
						&& cause == 0)
				{
					String tokenUserID = obj.get("TokenUserID").getAsString();
					String userID = obj.get("UserID").getAsString();

					String svrIp = SysConfig.getServerInfo().getIp();
//					int sipSvrPort = obj.get("PASPort").getAsInt();
//
//					String gisSvrIp = obj.get("GASAddr").getAsString();
//					int gisSvrPort = obj.get("GASport").getAsInt();
//
//					String fileSvrIp = obj.get("FASAddr").getAsString();
//					int fileSvrPort = obj.get("FASPort").getAsInt();
					int sipSvrPort = obj.get("PASSipPort").getAsInt();
					int gasSvrPort = obj.get("GASHttpPort").getAsInt();
					int masSvrPort = obj.get("MASHttpPort").getAsInt();
					int hasAlarm = 0;
					if(obj.get("Alarm") != null) {
						hasAlarm = obj.get("Alarm").getAsInt();
					}

					Log.debug(getClass(), "onResponse userID = " + userID + " tokenUserID = " + tokenUserID + " hasAlarm = " + hasAlarm);
					Log.debug(getClass(), "onResponse svrIp = " + svrIp + " sipSvrPort = " + sipSvrPort + " gasSvrPort = " + gasSvrPort + " masSvrPort = " + masSvrPort);
					config.setServerInfo(svrIp, sipSvrPort);
					config.setFileServerInfo(svrIp,masSvrPort);
					config.setGisServerInfo(svrIp,gasSvrPort);
					config.setUserID(userID,tokenUserID);
					config.setAlarm(hasAlarm);
					sendOpResultMsg(true,0);
				}
				else
				{
					sendOpResultMsg(false,cause);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				sendOpResultMsg(false,70090);
			}
		}
		else
		{
			sendOpResultMsg(false,70091);
			//	    notifyFailed(parserCallback,"readFromSvr code = " + code);
		}
	}
}
